import React from 'react';
import { Upload, message } from 'antd';
import upload from './useUploadPublic';

function UploadPublic(props, ref) {
    const {
        fileList = [],
        children,
        draggable = false,
        checkFileType = '',
        checkFileSize = 0,
        checkFileTypeMsg = null,
        checkFileSizeMsg = null,
        onChange,
        ...rest
    } = props;

    // 校验上传文件类型
    const checkUpload = (file, fileListTemp) => {
        if (checkFileType.length > 0) {
            const fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
            if (!checkFileType.toLocaleLowerCase().includes(fileType.toLocaleLowerCase())) {
                if (checkFileTypeMsg) {
                    message.error(checkFileTypeMsg);
                } else {
                    message.error(`You can only upload ${checkFileType}`);
                }
                fileListTemp.splice(fileListTemp.indexOf(file), 1);
                return false;
            }
        }

        if (checkFileSize > 0) {
            const isLess = file.size / 1024 / 1024 < checkFileSize;
            if (!isLess) {
                if (checkFileSizeMsg) {
                    message.error(checkFileSizeMsg);
                } else {
                    message.error(`File must smaller than ${checkFileSize}MB!`);
                }

                fileListTemp.splice(fileListTemp.indexOf(file), 1);
                return false;
            }
        }
        return true;
    };

    const customRequest = async options => {
        const { onSuccess, onError, file, onProgress } = options;
        const result = await upload(file, { onProgress, onSuccess, onError });
        if (result) {
            onSuccess(result);
        } else {
            onError();
        }
    };

    const handleRemove = file => {
        const files = fileList.filter(v => v.url !== file.url);
        if (onChange) {
            onChange(files);
        }
    };

    const handleChange = async info => {
        const { fileList: arr } = info;
        const tempFileList = arr.map(file => {
            let url = null;
            if (file.response) {
                url = { url: file.response };
            }
            return { ...file, ...url };
        });
        if (onChange) {
            onChange(tempFileList);
        }
    };

    const Component = draggable ? Upload.Dragger : Upload;

    return (
        <Component
            ref={ref}
            customRequest={customRequest}
            onRemove={handleRemove}
            onChange={handleChange}
            fileList={fileList}
            beforeUpload={checkUpload}
            {...rest}
        >
            {children}
        </Component>
    );
}

export default React.forwardRef(UploadPublic);
